package com.dy.system.service.impl;

import com.dy.basic.service.impl.BaseServiceImpl;
import com.dy.system.domain.Menu;
import com.dy.system.domain.Permission;
import com.dy.system.domain.Role;
import com.dy.system.mapper.MenuMapper;
import com.dy.system.mapper.PermissionMapper;
import com.dy.system.mapper.RoleMapper;
import com.dy.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dayong
 * @since 2023-03-09
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    // 菜单权限
    @Autowired
    private MenuMapper menuMapper;

    // 按钮权限
    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 添加角色信息
     */
    @Override
    @Transactional
    public void add(Role role) {
        // 添加role表的信息
        roleMapper.add(role);
        // 添加role-menu 中间表的信息
        menuMapper.addRoleMenu(role.getId(), role.getMenus());
        // 添加role-permission的信息
        permissionMapper.addRolePerm(role.getId(),role.getPermissions());
    }

    /**
     * 修改角色表的信息
     */
    @Override
    @Transactional
    public void update(Role role) {
        // 思路: 修改是先删除用户的信息，在添加用户的信息
        // 删除用户role表的信息
        roleMapper.delete(role.getId());
        // 删除menu_role表的信息
        menuMapper.deleteByRoleId(role.getId());
        // 删除role_perssion表的信息
        permissionMapper.deleteByPerId(role.getId());
        // 添加用户的信息
        add(role);
    }

    /**
     * 删除用户的信息
     * @param id
     */
    @Override
    @Transactional
    public void delete(Long id) {
        Role role = roleMapper.findById(id);
        // 删除两张中间表的数据
            // 查询两张中间表的信息
        Long menuid = menuMapper.findByRoleId(role.getId());
        Long permissionId = permissionMapper.findByRoleId(role.getId());

        // 删除两张中间表的数据
        menuMapper.deleteBymenuid(menuid);
        permissionMapper.deleteBypermissionId(permissionId);
        roleMapper.delete(id);
    }

}
